package com.dc.seckill.controller;

import com.dc.seckill.domain.MiaoshaOrder;
import com.dc.seckill.domain.MiaoshaUser;
import com.dc.seckill.domain.OrderInfo;
import com.dc.seckill.result.CodeMsg;
import com.dc.seckill.service.GoodsService;
import com.dc.seckill.service.MiaoshaService;
import com.dc.seckill.service.OrderService;
import com.dc.seckill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Created by djs on 2018/3/21.
 */
@Controller
@RequestMapping("/miaosha")
public class MiaoshaController {

    private Logger log = LoggerFactory.getLogger(MiaoshaController.class);

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;


    @RequestMapping("/do_miaosha")
    public String miaosha(Model model, MiaoshaUser user,
                          @RequestParam("goodsId") Long goodsId){

        if(user == null){
            log.info("用户未登录，跳往登录");
            return "login";
        }

        //1:判断库存
        GoodsVo goods = goodsService.queryGoodsVoByGoodsID(goodsId);
        if(goods == null){
            log.info("通过商品ID【"+goodsId+"】未找到商品");
            model.addAttribute("errmsg", CodeMsg.GOODS_NOT_EXIST.getMsg());
            return "miaosha_fail";
        }

        Integer stock = goods.getStockCount();
        Integer miaoshaStock = goods.getStockCount();
        log.info("该商品库存【"+stock+"】秒杀库存【"+miaoshaStock+"】");
        if(stock <= 0 || miaoshaStock <= 0){
            model.addAttribute("errmsg", CodeMsg.MIAO_SHA_OVER.getMsg());
            return "maiosha_fail";
        }

        //2:检查是否已经秒杀过
        MiaoshaOrder miaoshaOrder = orderService.queryOrderByUserIdGoodsId(user.getId(),goods.getId());
        if(miaoshaOrder != null){
            log.info("用户【"+user.getId()+"】已经进行过秒杀");
            model.addAttribute("errmsg",CodeMsg.MIAO_SHA_OVER.getMsg());
            return "maiosha_fail";
        }

        //3:进行秒杀操作
        OrderInfo orderInfo = miaoshaService.miaosha(user,goods);
        log.info("秒杀完成");
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("goods",goods);
        return "order_detail";
    }

}
